var express = require("express");
var router = express.Router();
const db = require("../db");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.redirect("/login");
});

router.get("/home", (req, res, next) => {
  if (req.session.userName) {
    res.render("index.ejs");
  } else {
    res.redirect("login");
  }
});

router.get("/login", function (req, res, next) {
  res.render("login.ejs");
});

router.post("/login", (req, res, next) => {
  db.getUser(req.body, (data) => {
    if (data) {
      console.log(data)
      req.session.userName = data.username;
      res.redirect("/home");
    } else {
      res.json('请输入正确的用户名和密码!')
    }
  });
});

// 退出登录
router.get("/logout", function (req, res) {
  req.session.userName = null; // 删除session
  res.redirect("login");
});
module.exports = router;
